package com.studyyoun.android.nonghe.home.activity;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera;
import android.media.MediaPlayer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.studyyoun.android.androidcommonbaselibrary.okhttp.callback.OkhttpCommonCallBack;
import com.studyyoun.android.androidcommonbaselibrary.okhttp.client.OkhttpCommonClient;
import com.studyyoun.android.androidcommonbaselibrary.utils.LogUtils;
import com.studyyoun.android.androidcommonbaselibrary.utils.ToastUtils;

import com.studyyoun.android.nonghe.R;
import com.studyyoun.android.nonghe.home.model.CheckResultModel;
import com.studyyoun.android.nonghe.home.model.CheckStatueRunModel;
import com.studyyoun.android.nonghe.home.model.CheckUserFaceModel;
import com.studyyoun.android.nonghe.home.model.HomeMsgMainModel;
import com.studyyoun.android.nonghe.http.HttpUrlHelper;
import com.studyyoun.android.nonghe.welcom.CommonUserHelper;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;

import io.vov.vitamio.utils.Base64;
import io.vov.vitamio.utils.Log;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


/**
 * Created by androidlongs on 16/8/3.
 */
public class ScanFaceActivity extends CommonBaseActivity implements SurfaceHolder.Callback, Camera.PreviewCallback {

    private SurfaceView surfaceView;
    private SurfaceHolder mHolder;

    /**
     * 页面扫描说明
     */
    private TextView mScanExplanTextView;
    /**
     * 退出当前页面
     */
    private RelativeLayout mBackRelativeLayout;
    private Camera.Size optimalSize;
    /**
     * 切图View
     */
    private View clip_square;
    private ImageView mHeaderImageView;
    private List<CheckStatueRunModel> mCheckStatueRunModels;


    @Override
    public int getViewLayoutId() {
        return R.layout.activity_scan_face;
    }

    @Override
    public void getAllExtarDatas() {

    }

    @Override
    public void initAllView() {

        mHeaderImageView = findViewById(R.id.iv_scan_header);

        mHeaderImageView.setVisibility(View.GONE);
        surfaceView = (SurfaceView) findViewById(R.id.activity_face_sfv_camera);
        mHolder = surfaceView.getHolder();
        //为了实现照片预览功能，需要将SurfaceHolder的类型设置为PUSH
        //这样，画图缓存就由Camera类来管理，画图缓存是独立于Surface的
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        mHolder.addCallback(this);


        mScanExplanTextView = (TextView) findViewById(R.id.tv_tips);

        mBackRelativeLayout = (RelativeLayout) findViewById(R.id.btn_back_container);

        clip_square = findViewById(R.id.clip_square);

    }

    @Override
    public void setAllViewClick() {
        mBackRelativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ScanFaceActivity.this.finish();
            }
        });
    }

    @Override
    public void displayRequestNetData() {

    }

    /**
     * 扫描类型标识
     */
    private int type = 0;

    @Override
    public void setCommonFunction() {


        String url = HttpUrlHelper.sUserCheckFaceUrl;

        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
        key.put("userId", CommonUserHelper.getUserModel().getData().getUserId() + "");
        key.put("flag", "2");
        key.put("photoUrl", "");

        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
            @Override
            public void onSuccess(Object obj) {


            }

            @Override
            public void onFaile(Object obj) {

            }
        });

    }

    // 0表示后置，1表示前置
    public static int cameraPosition = 1;
    private Camera mCamera;
    private Camera.Parameters params;

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        playVoiceItemStart();
        if (this.checkCameraHardware(this) && mCamera == null) {
            // 打开camera
            mCamera = getCamera(cameraPosition);
            if (mCamera != null) {
                params = mCamera.getParameters();

                if (mHolder != null) {
                    setStartPreview(mCamera, mHolder);
                    initCamPreView(this.getResources().getDisplayMetrics().widthPixels, this.getResources().getDisplayMetrics().heightPixels);
                }
            }
        }
    }

    private void initCamPreView(int ScreenWidth, int ScreenHeight) {
        cacheW = ScreenWidth;
        cacheH = ScreenHeight;

        if (optimalSize != null) {
            float lScaledDensity = this.getResources().getDisplayMetrics().scaledDensity;
            int minSide = (int) (lScaledDensity * 10);
            float step = 0.01f;
            int cacheW = optimalSize.height;  //取得摄像头参数是横屏参数
            int cacheH = optimalSize.width;

            while (cacheW < ScreenWidth - minSide && cacheH < ScreenHeight - minSide) {
                cacheW *= 1 + step;
                cacheH *= 1 + step;
            }
        }
    }

    /**
     * 设置camera显示取景画面,并预览 设置camera显示取景画面
     *
     * @param camera
     */
    private void setStartPreview(Camera camera, SurfaceHolder holder) {
        WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        Display display = manager.getDefaultDisplay();
        if (params == null) return;
        List<Camera.Size> sizes = params.getSupportedPreviewSizes();
        optimalSize = getOptimalPreviewSize1(sizes, display.getWidth(), display.getHeight());

        params.setPreviewSize(optimalSize.width, optimalSize.height);


//            L.i("RB", "\ndisplay.W:" + cacheSize.x + "\ndisplay.H:" + cacheSize.y +
//                    "\noptimal.W:" + optimalSize.width + "\noptimal.H:" + optimalSize.height);

        try {
            if (mCamera != null && params != null && holder != null) {
                mCamera.setParameters(params);
                mCamera.setDisplayOrientation(90);
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private Camera.Size getOptimalPreviewSize1(List<Camera.Size> sizes, int h, int w) {
        double targetRatio = (double) w / h;
        if (sizes == null)
            return null;

        Camera.Size optimalSize = null;
        double diff = Math.abs(((double) sizes.get(0).width / sizes.get(0).height) - targetRatio);

        for (Camera.Size size : sizes) {
            double ratio = (double) size.width / size.height;
            if (Math.abs(ratio - targetRatio) <= diff) {
                optimalSize = size;
                diff = Math.abs(ratio - targetRatio);
            }
        }

        if (null == optimalSize) {
            optimalSize = sizes.get(0);
        }

        return optimalSize;

    }

    /**
     * Check if this device has a camera
     */
    private boolean checkCameraHardware(Context context) {
        if (context.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_CAMERA)) {
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /**
     * create camera
     *
     * @param cameraIndex
     * @return
     */
    private Camera getCamera(int cameraIndex) {
        Camera camera = null;
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                == PackageManager.PERMISSION_GRANTED) {
            Log.i("TEST", "Granted");
            //init(barcodeScannerView, getIntent(), null);
        } else {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA}, 1);//1 can be another integer
        }
        try {
            camera = Camera.open(cameraIndex);
        } catch (Exception e) {
            // Camera is not available (in use or does not exist)
            //ToastUtils.show("打开像机异常", mAppContext);
            camera = null;
//            Log.e(TAG, "Camera is not available (in use or does not exist)");
        }
        return camera;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        /**
         * 记得释放camera，方便其他应用调用
         */
        releaseCamera();
    }

    /**
     * 释放mCamera
     */
    private void releaseCamera() {
        if (mCamera != null) {
            mCamera.stopPreview();// 停掉原来摄像头的预览
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        isForeground = true;
        startTimer(0);
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTimer();
        isForeground = false;
    }

    private boolean isForeground = false;
    private ClipTask clipTask;
    private Timer mTimer;
    private int mTimeUnit = 100;//多少ms截一帧图片

    private void startTimer(long delay) {
        if (null == mTimer) {
            mTimer = new Timer();
            clipTask = new ClipTask();
            mTimer.schedule(clipTask, delay, mTimeUnit);
        }
    }

    private void stopTimer() {
        if (null != mTimer) {
            mTimer.cancel();
            mTimer = null;
        }
        if (null != clipTask) {
            clipTask.cancel();
            clipTask = null;
        }
    }

    class ClipTask extends TimerTask {
        @Override
        public void run() {
            if (mCamera != null && mTimer != null && clipTask != null && isForeground)
                try {
                    mCamera.setOneShotPreviewCallback(ScanFaceActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }
        }
    }

    /**
     * 记录拍照次数
     */
    private int num = 0;
    private YuvImage yuvimage;
    private ByteArrayOutputStream baos;
    private Bitmap bitmap;
    private int cacheW = 0;  //预览宽
    private int cacheH = 0;  //预览高
    private float camRatio;
    private float scaleRatio;
    private float finalRatio;

    public boolean isSuccess = true;
    public int checkCount = 0;


    @Override
    public void onPreviewFrame(byte[] data, Camera camera) {
        num += 1;
        if (data != null && camera != null && num > 3 && isStart&&!isNetLoading) {

            //这里byte[] 不能直接用decodeByteArray生成bitmap，需要这段代码转换一下byte[]
            yuvimage = new YuvImage(data, ImageFormat.NV21, optimalSize.width, optimalSize.height, null);
            baos = new ByteArrayOutputStream();
            yuvimage.compressToJpeg(new Rect(0, 0, optimalSize.width, optimalSize.height), 100, baos);
            byte[] jdata = baos.toByteArray();
            bitmap = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);
            if (bitmap != null) {

                //得到图片第一步先缩小
                // 预览高 比上 摄像头 选择最佳分辨率后 拍摄出的图片 高


                if (cameraPosition == 1) {
                    //逆时针旋转90度，恢复竖直状态
                    bitmap = BitmapUtils.rotaingImage(-90, bitmap);
                } else if (cameraPosition == 0) {
                    //逆时针旋转90度，恢复竖直状态
                    bitmap = BitmapUtils.rotaingImage(90, bitmap);
                }


                bitmap = zoomImage(bitmap, 480, 640);
                String lS = bitmapToBase64(bitmap);
                //LogUtils.d(lS);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
                byte[] appicon = baos.toByteArray();// 转为byte数组
                lS = Base64.encodeToString(appicon, Base64.DEFAULT);

                //mHeaderImageView.setImageBitmap(bitmap);
                //File lFile = compressImage(bitmap);


                int lWidth = bitmap.getWidth();
                int lHeight = bitmap.getHeight();
                LogUtils.d("lWidth " + lWidth);
                LogUtils.d("lHeight " + lHeight);
                LogUtils.d("isLoading " + isLoading);
                if (!bitmap.isRecycled()) {
                    bitmap.recycle();
                    bitmap=null;
                }


                if (isLoading == 1 && !isNetLoading) {
                    isLoading = 2;
                    stopTimer();
                    isNetLoading = true;

                    String url = HttpUrlHelper.sfacerecognizeFaceUrl;


                    ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
                    key.put("UserGroupId", CommonUserHelper.getUserModel().getData().getUserGroupId() + "");
                    key.put("RawImage", lS);

                    //uploadImg(url,key,lFile);

                    mScanExplanTextView.setText("正在进行人脸识别");
                    OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(CheckUserFaceModel.class) {
                        @Override
                        public void onSuccess(Object obj) {
                            isNetLoading = false;
                            checkCount++;
                            if (obj != null) {
                                CheckUserFaceModel lCheckUserFaceModel = (CheckUserFaceModel) obj;
                                boolean lSuccess = lCheckUserFaceModel.isSuccess();
                                if (lSuccess) {
                                    isSuccess = true;
                                    checkCount = 0;
                                    LogUtils.d("人脸识别成功");
                                    //ToastUtils.show("人脸识别成功", mAppContext);
                                    GetRandomOperationsFunction();
                                } else {
                                    if (checkCount >= 3) {
                                        checkCount = 0;
                                        isSuccess=false;
                                        LogUtils.d("人脸识别失败");
                                        GetRandomOperationsFunction();
                                    } else {
                                        startTimer(mTimeUnit);
                                        isLoading = 1;
                                        //mScanExplanTextView.setText("人脸校验失败 请对准镜头");
                                        //ToastUtils.show("人脸识别失败 请对准镜头", mAppContext);
                                        //mScanExplanTextView.setText("请对准镜头");
                                        //GetRandomOperationsFunction();
                                    }
                                }
                            } else {

                                if (checkCount >= 3) {
                                    checkCount = 0;
                                    isSuccess = false;
                                    LogUtils.d("人脸识别失败");
                                    GetRandomOperationsFunction();
                                } else {
                                    startTimer(mTimeUnit);
                                    isLoading = 1;
                                    //mScanExplanTextView.setText("人脸校验失败 请对准镜头");
                                    ////ToastUtils.show("人脸校验失败 请对准镜头", mAppContext);
                                    //mScanExplanTextView.setText("请对准镜头");
                                    //GetRandomOperationsFunction();
                                }
                            }

                        }

                        @Override
                        public void onFaile(Object obj) {
                            isNetLoading = false;
                            isLoading = 1;
                            //mScanExplanTextView.setText("人脸校验失败 网络服务异常 正在重新校验");
                            ////ToastUtils.show("人脸识别失败 网络服务异常 正在重试", mAppContext);
                            checkCount++;
                            if (checkCount >= 3) {
                                checkCount = 0;
                                isSuccess = false;
                                LogUtils.d("人脸识别失败");
                                GetRandomOperationsFunction();
                            } else {
                                startTimer(mTimeUnit);
                                isLoading = 1;
                                //mScanExplanTextView.setText("人脸校验失败 请对准镜头");
                                ////ToastUtils.show("人脸校验失败 请对准镜头", mAppContext);
                                //mScanExplanTextView.setText("请对准镜头");
                                //GetRandomOperationsFunction();
                            }
                        }
                    });
                } else if (isLoading == 3 && !isNetLoading) {

                    stopTimer();
                    isNetLoading = true;

                    LogUtils.d("isLoading is 3 ");

                    if (mCheckStatueRunModels != null && mCheckStatueRunModels.size() == 3) {
                        String url = HttpUrlHelper.sprocessimageUrl;

                        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
                        key.put("OperationId", mCheckStatueRunModels.get(0).getId() + "");
                        key.put("RawImage", lS);

                        //uploadImg(url,key,lFile);


                        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(CheckResultModel.class) {
                            @Override
                            public void onSuccess(Object obj) {
                                isNetLoading = false;
                                if (obj != null) {
                                    checkCount++;

                                    CheckResultModel checkResultModel = (CheckResultModel) obj;
                                    LogUtils.e("checkResultModel isSuccess " + checkResultModel.isSuccess());
                                    if (checkResultModel.isSuccess()) {
                                        checkCount = 0;
                                        LogUtils.d("动作一检测 成功");
                                        palayVoiceItem2();
                                    } else {

                                        if (checkCount >= 3) {
                                            isSuccess = false;
                                            checkCount = 0;
                                            LogUtils.d("动作一检测 失败");
                                            palayVoiceItem2();
                                        } else {
                                            isLoading = 3;
                                            startTimer(mTimeUnit);
                                            CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(0);
                                            String lName = lCheckStatueRunModel.getName();
                                            String lTips = lCheckStatueRunModel.getTips();
                                            String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                            //mScanExplanTextView.setText("检测失败 请  " + lTips);
                                        }

                                    }
                                } else {

                                    if (checkCount >= 3) {
                                        isSuccess = false;
                                        checkCount = 0;
                                        LogUtils.d("动作一检测 失败");
                                        palayVoiceItem2();
                                    } else {
                                        isLoading = 3;
                                        startTimer(mTimeUnit);
                                        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(0);
                                        String lName = lCheckStatueRunModel.getName();
                                        String lTips = lCheckStatueRunModel.getTips();
                                        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                        //mScanExplanTextView.setText("检测失败 请  " + lTips);
                                    }
                                }

                            }

                            @Override
                            public void onFaile(Object obj) {
                                isNetLoading = false;
                                checkCount++;
                                isLoading = 3;
                                //mScanExplanTextView.setText("检测失败 网络服务异常 正在重试  ");
                                ////ToastUtils.show("人脸校验失败 网络服务异常 ", mAppContext);
                                if (checkCount >= 3) {
                                    isSuccess = false;
                                    checkCount = 0;
                                    LogUtils.d("动作一检测 失败");
                                    palayVoiceItem2();
                                } else {
                                    startTimer(mTimeUnit);
                                }
                            }
                        });
                    }


                } else if (isLoading == 4 && !isNetLoading) {

                    stopTimer();
                    isNetLoading = true;

                    if (mCheckStatueRunModels != null && mCheckStatueRunModels.size() == 3) {
                        String url = HttpUrlHelper.sprocessimageUrl;

                        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
                        key.put("OperationId", mCheckStatueRunModels.get(1).getId() + "");
                        key.put("RawImage", lS);

                        //uploadImg(url,key,lFile);


                        mCall = OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(CheckResultModel.class) {
                            @Override
                            public void onSuccess(Object obj) {
                                isNetLoading = false;
                                if (obj != null) {
                                    checkCount++;
                                    CheckResultModel checkResultModel = (CheckResultModel) obj;
                                    if (checkResultModel.isSuccess()) {
                                        checkCount = 0;
                                        LogUtils.d("动作二检测 成功");
                                        playVoiceItem3();
                                    } else {

                                        if (checkCount >= 3) {
                                            isSuccess = false;
                                            checkCount = 0;
                                            LogUtils.d("动作二检测 失败");
                                            playVoiceItem3();
                                        } else {
                                            CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(1);
                                            String lName = lCheckStatueRunModel.getName();
                                            String lTips = lCheckStatueRunModel.getTips();
                                            String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                            //mScanExplanTextView.setText("检测失败 请  " + lTips);
                                            //ToastUtils.show("请对准屏幕 " + lTips, mAppContext);

                                            startTimer(mTimeUnit);
                                        }

                                    }
                                } else {
                                    if (checkCount >= 3) {
                                        isSuccess = false;
                                        checkCount = 0;
                                        LogUtils.d("动作二检测 失败");
                                        playVoiceItem3();
                                    } else {


                                        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(1);
                                        String lName = lCheckStatueRunModel.getName();
                                        String lTips = lCheckStatueRunModel.getTips();
                                        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                        //mScanExplanTextView.setText("检测失败 请  " + lTips);
                                        //ToastUtils.show("请对准屏幕 " + lTips, mAppContext);

                                        startTimer(mTimeUnit);

                                    }
                                }
                            }

                            @Override
                            public void onFaile(Object obj) {
                                isNetLoading = false;
                                //mScanExplanTextView.setText("检测失败 网络服务异常 正在重试  ");
                                //ToastUtils.show("人脸校验失败 网络服务异常 ", mAppContext);
                                isLoading = 4;
                                if (checkCount >= 3) {
                                    LogUtils.d("动作二检测 失败");
                                    isSuccess = false;
                                    checkCount = 0;
                                    playVoiceItem3();
                                } else {
                                    startTimer(mTimeUnit);
                                }
                            }
                        });
                    }


                } else if (isLoading == 5 && !isNetLoading) {


                    stopTimer();
                    isNetLoading = true;
                    if (mCheckStatueRunModels != null && mCheckStatueRunModels.size() == 3) {
                        String url = HttpUrlHelper.sprocessimageUrl;

                        ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
                        key.put("OperationId", mCheckStatueRunModels.get(2).getId() + "");
                        key.put("RawImage", lS);

                        //uploadImg(url,key,lFile);


                        OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack(CheckResultModel.class) {
                            @Override
                            public void onSuccess(Object obj) {
                                isNetLoading = false;
                                if (obj != null) {
                                    checkCount++;
                                    CheckResultModel checkResultModel = (CheckResultModel) obj;
                                    if (checkResultModel.isSuccess()) {

                                        if (!isSuccess) {

                                            playVoiceItem4();
                                        } else {

                                            LogUtils.e("检测完毕");


                                            String url = HttpUrlHelper.sUserCheckFaceUrl;

                                            ConcurrentHashMap<String, String> key = new ConcurrentHashMap<>();
                                            key.put("userId", CommonUserHelper.getUserModel().getData().getUserId() + "");
                                            key.put("flag", "1");
                                            key.put("photoUrl", "");

                                            OkhttpCommonClient.sentPostRequest(url, key, new OkhttpCommonCallBack() {
                                                @Override
                                                public void onSuccess(Object obj) {

                                                    //检测成功
                                                    //ToastUtils.show("检测完成", mAppContext);
                                                    playVoiceItem5();


                                                }

                                                @Override
                                                public void onFaile(Object obj) {
                                                    playVoiceItem4();
                                                }
                                            });
                                        }
                                    } else {

                                        if (checkCount >= 3) {
                                            LogUtils.d("动作三检测 失败");
                                            playVoiceItem4();
                                        } else {

                                            CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(2);
                                            String lName = lCheckStatueRunModel.getName();
                                            String lTips = lCheckStatueRunModel.getTips();
                                            String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                            mScanExplanTextView.setText("请对准屏幕 " + lTips);
                                            startTimer(mTimeUnit);
                                        }

                                    }
                                } else {
                                    if (checkCount >= 3) {
                                        playVoiceItem4();
                                    } else {
                                        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(2);
                                        String lName = lCheckStatueRunModel.getName();
                                        String lTips = lCheckStatueRunModel.getTips();
                                        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                                        mScanExplanTextView.setText("请对准屏幕 " + lTips);
                                        startTimer(mTimeUnit);
                                    }

                                }

                            }

                            @Override
                            public void onFaile(Object obj) {
                                isNetLoading = false;
                                checkCount++;
                                //ToastUtils.show("人脸校验失败 网络服务异常 ", mAppContext);
                                isLoading = 5;
                                if (checkCount >= 3) {
                                    playVoiceItem4();
                                } else {

                                    startTimer(mTimeUnit);
                                }
                            }
                        });
                    }


                }

            }
        }

    }

    private boolean isStart = false;
    private boolean isNetLoading = false;
    public Handler mHandler = new Handler(Looper.getMainLooper());

    private void playVoiceItemStart() {
        String lVoice = HttpUrlHelper.BaseHost3 + "/audio/statr.mp3";
        mMediaPlayer = createNetMp3(lVoice);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();//释放音频资源

                        isStart = true;


            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //开始播放音频
                mMediaPlayer.start();
            }
        });
        try {
            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
            mMediaPlayer.prepare();

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playVoiceItem5() {
        String lVoice = HttpUrlHelper.BaseHost3 + "/audio/success.mp3";
        mMediaPlayer = createNetMp3(lVoice);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();//释放音频资源
                ScanFaceActivity.this.finish();
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //开始播放音频
                mMediaPlayer.start();
            }
        });
        try {
            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
            mMediaPlayer.prepare();

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playVoiceItem4() {
        String lVoice = HttpUrlHelper.BaseHost3 + "/audio/fail.mp3";
        mMediaPlayer = createNetMp3(lVoice);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();//释放音频资源

                ScanFaceActivity.this.finish();
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //开始播放音频
                mMediaPlayer.start();
            }
        });
        try {
            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
            mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void playVoiceItem3() {
        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(2);
        String lName = lCheckStatueRunModel.getName();
        String lTips = lCheckStatueRunModel.getTips();
        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

        mScanExplanTextView.setText("动作校验 " + lTips);
        //ToastUtils.show("请对准屏幕 " + lTips, mAppContext);

        if (mMediaPlayer != null) {
            mMediaPlayer.release();
        }

        mMediaPlayer = createNetMp3(lVoice);
        createState = true;

        isLoading = 5;
        //当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
        //以便其他应用程序可以使用该资源:
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.release();//释放音频资源

                startTimer(mTimeUnit);
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //开始播放音频
                mMediaPlayer.start();
            }
        });
        try {
            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
            if (createState) mMediaPlayer.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void palayVoiceItem2() {
        LogUtils.e("checkResultModel isSuccess 233");
        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(1);
        String lName = lCheckStatueRunModel.getName();
        String lTips = lCheckStatueRunModel.getTips();
        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

        mScanExplanTextView.setText("动作校验 " + lTips);
        //ToastUtils.show("请对准屏幕 " + lTips, mAppContext);

        if (mMediaPlayer != null) {

            mMediaPlayer.release();

        }
        mMediaPlayer = createNetMp3(lVoice);
        createState = true;

        isLoading = 4;
        LogUtils.e("checkResultModel isSuccess 234");
        //当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
        //以便其他应用程序可以使用该资源:
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                //释放音频资源
                mMediaPlayer.release();
                startTimer(mTimeUnit);
                LogUtils.e("checkResultModel isSuccess 235");
            }
        });
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                //开始播放音频
                mMediaPlayer.start();
            }
        });
        try {
            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
            if (createState) mMediaPlayer.prepare();

        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("恐怖党 " + e.getMessage());
        }
    }

    private MediaPlayer mMediaPlayer;
    private boolean createState = false;

    private void GetRandomOperationsFunction() {
        isNetLoading = true;

        String url = HttpUrlHelper.sGetRandomOperationsUrl;
        OkhttpCommonClient.sentGetRequest(url, null, new OkhttpCommonCallBack(CheckStatueRunModel.class) {
            @Override
            public void onSuccess(Object obj) {
                isNetLoading = false;
                if (obj != null) {
                    mCheckStatueRunModels = (List<CheckStatueRunModel>) obj;

                    if (mCheckStatueRunModels.size() == 3) {
                        CheckStatueRunModel lCheckStatueRunModel = mCheckStatueRunModels.get(0);
                        String lName = lCheckStatueRunModel.getName();
                        String lTips = lCheckStatueRunModel.getTips();
                        String lVoice = HttpUrlHelper.BaseHost3 + lCheckStatueRunModel.getVoice();

                        mScanExplanTextView.setText("" + lTips);
                        mScanExplanTextView.setText("动作检测 " + lTips);

                        if (mMediaPlayer != null) {
                            mMediaPlayer.release();
                        }

                        mMediaPlayer = createNetMp3(lVoice);
                        createState = true;

                        //当播放完音频资源时，会触发onCompletion事件，可以在该事件中释放音频资源，
                        //以便其他应用程序可以使用该资源:
                        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                mp.release();//释放音频资源
                                isLoading = 3;
                                startTimer(mTimeUnit);
                            }
                        });
                        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                            @Override
                            public void onPrepared(MediaPlayer mp) {
                                //开始播放音频
                                mMediaPlayer.start();
                            }
                        });
                        try {
                            //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                            mMediaPlayer.prepare();
                        } catch (IllegalStateException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                } else {
                    //mScanExplanTextView.setText("动作检测获取失败 服务异常");
                    startTimer(mTimeUnit);
                }

            }

            @Override
            public void onFaile(Object obj) {
                startTimer(mTimeUnit);
                isNetLoading = false;
                //mScanExplanTextView.setText("动作检测获取失败 服务异常");
            }
        });
    }

    private int isLoading = 1;

    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {

        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    /***
     * 图片压缩方法二
     *
     * @param bgimage
     *            ：源图片资源
     * @param newWidth
     *            ：缩放后宽度
     * @param newHeight
     *            ：缩放后高度
     * @return
     */
    public Bitmap zoomImage(Bitmap bgimage, double newWidth, double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }


    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {  //循环判断如果压缩后图片是否大于500kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            options -= 10;//每次都减少10
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            long length = baos.toByteArray().length;
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date(System.currentTimeMillis());
        String filename = format.format(date);
        File file = new File(Environment.getExternalStorageDirectory(), filename + ".png");
        try {
            FileOutputStream fos = new FileOutputStream(file);
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        }
        //recycleBitmap(bitmap);
        return file;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private void uploadImg(String url, ConcurrentHashMap<String, String> list, File pFile) {

        // mImgUrls为存放图片的url集合
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        Set<Map.Entry<String, String>> lEntries = list.entrySet();
        for (Map.Entry<String, String> lEntry : lEntries) {
            builder.addFormDataPart(lEntry.getKey(), lEntry.getValue());
        }

        builder.addFormDataPart("RawImage", pFile.getName(), RequestBody.create(MEDIA_TYPE_PNG, pFile));


        //添加其它信息
//        builder.addFormDataPart("time",takePicTime);
//        builder.addFormDataPart("mapX", SharedInfoUtils.getLongitude());
//        builder.addFormDataPart("mapY",SharedInfoUtils.getLatitude());
//        builder.addFormDataPart("name",SharedInfoUtils.getUserName());


        MultipartBody requestBody = builder.build();
        //构建请求
        Request request = new Request.Builder()
                .url(url)//地址
                .post(requestBody)//添加请求体
                .build();

        OkHttpClient lOkHttpClient = new OkHttpClient();

        lOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                System.out.println("上传失败:e.getLocalizedMessage() = " + e.getLocalizedMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                System.out.println("上传照片成功：response = " + response.body().string());


            }
        });

    }

    /**
     * 创建网络mp3
     *
     * @return
     */
    public MediaPlayer createNetMp3(String url) {

        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }

    private Call mCall;

    @Override
    protected void onDestroy() {
        super.onDestroy();


        if (mCall != null) {
            mCall.cancel();
        }

        mHandler.removeCallbacksAndMessages(0);

        stopTimer();

        if (mMediaPlayer != null) {
            mMediaPlayer.release();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        if (this.checkCameraHardware(this) && mCamera == null) {
            // 打开camera
            mCamera = getCamera(cameraPosition);
            if (mCamera != null) {
                params = mCamera.getParameters();

                if (mHolder != null) {
                    setStartPreview(mCamera, mHolder);
                    initCamPreView(this.getResources().getDisplayMetrics().widthPixels, this.getResources().getDisplayMetrics().heightPixels);
                }
            }
        }
    }

}
